# -*- coding: utf-8 -*-

from multiprocessing import Pool
import time
import random
import os
import traceback

import py2_module
import py2_file

from py2_module import cost_time
from py2_module import functions


@functions("parameter")
@cost_time
def apply_func(text="info", path="log.log"):
    begin_time = time.time()
    n = 10 * random.random()
    line = "%s:%s" % (text, str(n))
    print(line)
    py2_file.write_aline(path, line)
    time.sleep(n)
    end_time = time.time()
    print("%s : %s" % ("apply_func", end_time - begin_time))
    pass


def map_func(text):
    n = 10 * random.random()
    print(text + str(n))
    time.sleep(n)
    pass


def test_pool():

    # path = "." + os.sep + "logs" + os.sep + "test.log"

    for i in range(2):
        pool = Pool(2)
        for j in range(6):
            path = "." + os.sep + str(i) + os.sep + str(j)
            text = "pool_" + str(i) + "_" + str(j) + "_sleep:"
            pool.apply_async(func=apply_func, args=(text, path,))
            print("i:" + str(i) + " j:" + str(j))
            pass
        pool.close()
        pool.join()

        print("i:" + str(i))
        pass

    print

    pass


def demo_pool():
    text = "sleep:"
    pool = Pool(2)
    for i in range(2):
        for j in range(2):
            pool.apply_async(func=apply_func, args=(text,))
            print("i:" + str(i) + " j:" + str(j))
            pass
        print("i:" + str(i))
        pass

    pool.close()
    pool.join()

    pass




if __name__ == '__main__':

    try:
        # test_pool()
        # test_pool()

        # demo_pool()

        text = "sleep:"
        path = "." + os.sep + "logs" + os.sep + "test.log"
        apply_func(text, path)




        # py2_module.test_func()

    except Exception as e:
        print(traceback.format_exc(e))

    finally:
        print("finally")
    pass
